<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .router-link-active{
      background-color: red;
    }
  </style>
</head>
<body>
  <div id="app">
    <router-link tag="button" to="/home">首页</router-link>
    <router-link tag="button" to="/news">新闻页</router-link>
    <router-link tag="button" to="/about">关于我们页</router-link>
    <!-- 手动指定路由组件的出口 -->
    <router-view></router-view>
  </div>
  <script src="./vue.js"></script>
  <script src="./vue-router.js"></script>
  <script>
    // 准备三个组件对象
    const Home = {
      template: `
        <div>
          <h2>我是首页</h2>  
        </div>
      `
    }
    const News = {
      template: `
        <div>
          <h2>我是新闻页</h2>  
        </div>
      `
    }
    const About = {
      template: `
        <div>
          <h2>我是关于我们页</h2>  
        </div>
      `
    }
    const Login = {
      template: `
        <div>
          <h2>我是登录页</h2>  
          <button @click="doLogin">登录</button>
        </div>
      `,
      methods: {
        doLogin(){
          setTimeout(()=>{
            const token = 'fhwijcr39yfe9r3fed';
            // 成功之后缓存token然后跳转
            localStorage.setItem('token', token);
            if(this.$route.query.from){
              this.$router.replace(this.$route.query.from);
            }else{
              this.$router.replace('/home');
            }
          
          },1000)
        }
      }
    }

    const routes = [
      {
        path: '/',
        redirect: '/home'
      },
      {
        path: '/home',
        component: Home
      },
      {
        path: '/news',
        component: News,
        beforeEnter: (to,from,next) => {
          const token = localStorage.getItem('token');
          if(token){
            next();
          }else{
            next({
              path: '/login',
              query: {
                from: '/news'
              }
            })
          }
        }
      },
      {
        path: '/about',
        component: About
      
      },
      {
        path: '/login',
        component: Login
      }
    ]
    // 创建路由实例
    const router = new VueRouter({
      // routes 路由规则 数组 有多个路由
      routes
    });
  
    const vm = new Vue({
      el: '#app',
      router
    })
  </script>
</body>
</html>